package com.sunmouse.thread;

import com.sunmouse.util.PrintUtil;


public class BreadSeller {
	
	
	
	int index = 0;
	Bread[] cap = new Bread[7];

	// use for imitating product
	public synchronized void push(Bread b) {
		if (index == cap.length) {
			try {
				this.wait();// if basket is full then wait
			} catch (Exception e) {
				e.printStackTrace(); // TODO: handle exception
			}
		}
		this.notifyAll();// be notified
		PrintUtil.pln(Thread.currentThread().getName()
				+ " is producting breads");
		cap[index] = b;
		index++;
	}

	// use for imitating consumer
	public synchronized Bread pop() {
		if (index == 0) {
			try {
				this.wait();
			} catch (Exception e) {
				e.printStackTrace(); // TODO: handle exception
			}
		}
		this.notifyAll();
		PrintUtil.pln(Thread.currentThread().getName()+" is eating breads");
		return cap[--index];
	}
	
	/**
	 * bread bean
	 * @author Administrator
	 *
	 */
	public static class Bread{
		
	}
	
	/**
	 * consumer thread
	 */
	public static class ConsumerThread implements Runnable{
		private BreadSeller bk;

		public ConsumerThread(BreadSeller bk) {
			super();
			this.bk = bk;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			for (int i = 1; i <= 10; i++) {
				bk.pop();
				try {
					Thread.sleep((int) (Math.random() * 5000));
				} catch (Exception e) {
					e.printStackTrace(); // TODO: handle exception
				}

			}
		}

	}
	
	/**
	 * Producer thread
	 */
	public static class ProducerThread implements Runnable{
		private BreadSeller bk;

		public ProducerThread(BreadSeller bk) {
			super();
			this.bk = bk;
		}

		@Override
		public void run() {
			for (int i = 0; i < 20; i++) {
				bk.push(new Bread());
				try {
					Thread.sleep((int) (Math.random() * 2000));
				} catch (Exception e) {
					e.printStackTrace();// TODO: handle exception
				}
			}
		}
	}
}


